package 网络编程.TCPFileCopy1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-05
 * Time: 17:34
 */
public class TCPFIleServer01 {

    ServerSocket serverSocket = null;

    public TCPFIleServer01(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器正在监听8000端口...");
        Socket socket = serverSocket.accept();
        processConnect(socket);
    }

    public void processConnect(Socket socket) throws IOException {
        System.out.println("服务器与客户端连接成功");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //服务器这边先要读取客户端想要得到的文件名
            String reqFileName = "";
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            int len = 0;
            byte[] bytes = new byte[1024];

            while((len = inputStream.read(bytes))!=-1){
                reqFileName = new String(bytes,0,len);
            }

            String respFileName = "";
            //查找目标文件,如果是高山流水返回高山流水,默认返回落井下石
            if("科尔沁夫 - 画你".equals(reqFileName)){
                respFileName = "src\\科尔沁夫 - 画你.mp3";
            }else {
                respFileName = "src\\科尔沁夫 - 画你.mp3";
            }

            //读取文件
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(respFileName));
            byte[] b = StreamUtil.streamByteArray(bis);

            //完成响应的文件之后,就可以发送给客户端了
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(b);
            bufferedOutputStream.flush();
            socket.shutdownOutput();//设置结束标记
            System.out.println("服务器成功发送...");
            //关闭对应的流
            bufferedInputStream.close();
            bis.close();
            bufferedOutputStream.close();
        } finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPFIleServer01 tcpfIleServer01 = new TCPFIleServer01(8000);
        tcpfIleServer01.start();
    }

}
